$(function() {
//Declare variable
	var tips = $( ".validateTips" ),
		POS=$("#POS"),
		Stock=$("#Stock"),
		Premium=$("#Premium"),
		button_name="",
		url="a_stock.php", 
		ID="",
		mode="",
		rowSelect="";
		
		//LoadData(1,false);
		//function showLoader(){
		$( "#resultData tbody:first" ).prepend( "<tr>"
					+"<td colspan='16' align='center' >"
					+"<img src='./images/info.gif'/><b/>"
					+"</td>"
					+"</tr>" ); 
						
		if  ($("#cboBranch").length > 0 ){
			$.get(url, {"c":"b"},function(data){
				//alert(data);
				$.each(eval('('+data+')'), function(index, text) {
					$("#cboBranch").append(
							$('<option></option>').val(text).html(index)
						 );
				});
			});	
			$("#cboBranch").append($('<option></option>').val(0).html('All'));
		}
		$("#cboBranch").combobox();
		$('.ui-autocomplete-input').css('width', '200px');
		
		$.get(url, {"c":"c"},function(data){
			$.each(eval('('+data+')'), function(index, text) {
				$("#cboCategory").append(
						$('<option></option>').val(index).html(text)
					 );
			});
		});	
		$("#cboCategory").append($('<option></option>').val(0).html('All'));
		
		$.get(url, {"c":"t"},function(data){
			 //alert(data);
			$.each(eval('('+data+')'), function(index, text) {
				$("#cboType").append(
						$('<option></option>').val(index).html(text)
					 );
			});
		});
		$("#cboType").append($('<option></option>').val(0).html('All'));
		//Show Loading bar			
		function showLoader(){
			var col=16;
			if($("#isHO").val()==1)
				col=16;
			else 
				col=16;
				
			$( "#resultData tbody:first" ).prepend( "<tr>"
						+"<td colspan="+col+" class='search-background'>"
						+"<label><img src='./images/ajax-loader.gif'/></label>"
						+"</td>"
						+"</tr>" ); 
			 $('.search-background').fadeIn(900,0);
		}
		//Hide Loading bar			
		function hideLoader(){
			$('.search-background').fadeOut(300);
			$( "#resultData tbody tr" ).remove();
		};
		$("#btnSearch").click(function(){
			LoadData (1,false)
		});
		
	
		$("input[name=txtstock]").live('keypress',function(e){
			
			if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57) && e.which!=46){
				return false;
			}
		});

		//b=false , don't gennerate paging
		function LoadData(page,b){
			$( "#resultData tbody tr" ).remove();
			//Show loading
			showLoader();
			//set criteria
			var branch=0;
			if ($("#cboBranch").length>0)
				branch=$("#cboBranch").val();
 
				
			 //Post 			
			var data={};
			data={'m':'view'
				,'branch':branch
				,'productname':$("#txtProduct").val()
				,'category':$("#cboCategory").val()			
				,'type':0//$("#cboType").val()	
				,'pos':POS.attr('checked')==true? 1:0
				,'stock':Stock.attr('checked')==true? 1:0
				,'premium':Premium.attr('checked')==true? 1:0
				,'page':page};
						
			$.post(url,data,function(data){
			 //alert(data);
				var obj=eval("(" + data + ")");
				//hide loading
				hideLoader();			
				//set data to table
				$( "#resultData tbody" ).append(obj['data']);
				//set row 
				$("#rowCount").attr('innerHTML',obj['rows']);
				//set page
				if (b){
					var p="<ul>";
					for (var i=parseInt(obj['totalpage']);i >0 ;i--){
						p = p +'<li id="'+i+'">'+i+'</li>';
					}
					p = p+"</ul>";
					$("#paging_button ul").remove();
					$("#paging_button").append(p);
					 
				}
				$("#"+page).css({'background-color' : '#006699'});
			});
	}
    	
	$("#btnPrint").live('click',function(){
		var po=POS.attr('checked')==true?'1':'0';
		var s=Stock.attr('checked')==true?'1':'0';
		var pr=Premium.attr('checked')==true?'1':'0'
		var branch=0;
		if ($("#rowCount").attr('innerHTML')!='0')
		 {
		if ($("#cboBranch").length>0)
				branch=$("#cboBranch").val();
			window.open('stock_print.php?b='+branch+'&p='+$("#txtProduct").val()+'&c='+$("#cboCategory").val()+'&po='+po+'&s='+s+'&pr='+pr+'','Stock','left=20,top=20,width=800,height=600,toolbar=1,resizable=1');
		}
	});
	
	$(".btnSave").live('click',function(){
		var rowSelect=$(this).parent().parent();
		var Amt= rowSelect.find("input[name=txtstock]").val();   
		var BranchID=rowSelect.find("td").eq(1).html();
		var ProductdID=rowSelect.find("td").eq(2).html();
		var rowID=rowSelect.find("td").eq(0).html();
		var btn=$(this);
		btn.attr('src','images/loading.gif');
		
	
		$.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: {"m":"update","amt":Amt,"pid":ProductdID,"bid":BranchID,"rows":rowID },
				success: function(data){
					//alert(data);
					rowSelect.html(data).css({color:'blue'});
					
				},
				complete:function(){
					alert('Update completed.');
					btn.attr('src','images/save24.png');
				}
			});
	});
	
	$("#paging_button li").live('click',function(){
		$("#paging_button li").css({'background-color' : ''});
 		LoadData(this.id,false);

	});
});

(function( $ ) {
		$.widget( "ui.combobox", {
		_create: function() {
				var self = this,
					select = this.element.hide(),
					selected = select.children( ":selected" ),
					value = selected.val() ? selected.text() : "";
				var input = this.input = $( "<input>" )
					.insertAfter( select )
					.val( value )
					.autocomplete({
						delay: 0,
						minLength: 0,
						source: function( request, response ) {
							var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
							response( select.children( "option" ).map(function() {
								var text = $( this ).text();
								if ( this.value && ( !request.term || matcher.test(text) ) )
									return {
										label: text.replace(
											new RegExp(
												"(?![^&;]+;)(?!<[^<>]*)(" +
												$.ui.autocomplete.escapeRegex(request.term) +
												")(?![^<>]*>)(?![^&;]+;)", "gi"
											), "<strong>$1</strong>" ),
										value: text,
										option: this
									};
							}) );
						},
						select: function( event, ui ) {
							ui.item.option.selected = true;
							self._trigger( "selected", event, {
								item: ui.item.option
							});
						},
						change: function( event, ui ) {
							if ( !ui.item ) {
								
								var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
									valid = false;
									select.children( "option" ).each(function() {
									if ( $( this ).text().match( matcher ) ) {
										this.selected = valid = true;
										return false;
									}
								});
								if ( !valid ) {
									// remove invalid value, as it didn't match anything
									$( this ).val( "" );
									select.val( "" );
									input.data( "autocomplete" ).term = "";
									return false;
								}
							}
						}
					})
					.addClass( "ui-widget ui-widget-content ui-corner-left" );
					
					input.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li></li>" )
						.data( "item.autocomplete", item )
						.append( "<a>" + item.label + "</a>" )
						.appendTo( ul );
				};

				this.button = $( "<button type='button'>&nbsp;</button>" )
					.attr( "tabIndex", -1 )
					.attr( "title", "Show All Items" )
					.insertAfter( input )
					.button({
						icons: {
							primary: "ui-icon-triangle-1-s"
						},
						text: false
					})
					.removeClass( "ui-corner-all" )
					.addClass( "ui-corner-right ui-button-icon" )
					.click(function() {
						// close if already visible
						if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
							input.autocomplete( "close" );
							return;
						}

						// pass empty string as value to search for, displaying all results
						input.autocomplete( "search", "" );
						input.focus();
					});
			}
		});
})( jQuery );	
	